package net.oschina.jhssm.common.controller;

import net.oschina.jhssm.common.entity.R;
import net.oschina.jhssm.common.exception.BusinessException;
import net.oschina.jhssm.common.util.HttpUtil;
import net.oschina.jhssm.module.system.service.ISysResourceService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;

/**
 * Created by zhaojb on 2017/8/20.
 */
@ControllerAdvice
public class WebAdvice {

    @Autowired
    private ISysResourceService resourceService;

    @ModelAttribute
    public void setModel(Model model, HttpServletRequest request) {
        model.addAttribute("baseUrl", HttpUtil.getBaseUrl(request));
        model.addAttribute("currentPath", request.getServletPath());
        model.addAttribute("user", SecurityUtils.getSubject().getPrincipal());
        model.addAttribute("shiro", SecurityUtils.getSubject());
        model.addAttribute("tree", resourceService.createNavTreeView());
    }

    @ExceptionHandler
    @ResponseBody
    public R handleError(Exception ex) {
        if (ex instanceof BusinessException) {
            //处理业务异常
            return R.error(ex.getMessage());
        } else if (ex instanceof UnauthorizedException) {
            return R.error("没有相应的权限");
        } else if (ex instanceof ValidationException) {
            return R.error("数据校验错误", "detail", ex.getMessage());
        } else {
            //处理系统异常
            ex.printStackTrace();
            return R.error("系统内部错误");
        }
    }
}
